package com.shihb.udtfs;

import java.util.ArrayList;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

/**
 *Description:自定义UDTF,按照指定分割符分割数据
 *Version:1.0.0
 *@author shihb
 *@date 2020/9/10 10:50
 */
public class Test extends GenericUDTF {
  private ArrayList<String> list = new ArrayList<>();

  @Override
  public StructObjectInspector initialize(StructObjectInspector argOIs)
      throws UDFArgumentException {
    // 定义输出数据的列名，可以生成多个列
    ArrayList<String> fieldNames = new ArrayList();
    fieldNames.add("result");
    // 定义函数的返回值
    ArrayList<ObjectInspector> fieldOIs = new ArrayList();
    fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
    return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
  }

  @Override
  public void process(Object[] args) throws HiveException {

    // 1获取数据
    String data = args[0].toString();
    // 2获取分隔符
    String splitKey = args[1].toString();
    // 3切分数据

    String[] words = data.split(splitKey);
    // 4遍历数据

    for (String word:words) {
      list.clear();
      list.add(word);
      // 5写出list,一个值就返回一个列,要返回多个列,对号入座
      forward(list);
    }

  }

  @Override
  public void close() throws HiveException {

  }
}
